import request from './axios'

export const teamApi = {
  // 获取团队列表
  getTeams(params) {
    return request({
      url: '/team/teams/',
      method: 'get',
      params
    })
  },

  // 创建团队
  createTeam(data) {
    return request({
      url: '/team/teams/',
      method: 'post',
      data: {
        ...data,
        creator: parseInt(localStorage.getItem('userId'))
      }
    })
  },

  // 更新团队信息
  updateTeam(id, data) {
    return request({
      url: `/team/teams/${id}/`,
      method: 'put',
      data
    })
  },

  // 删除团队
  deleteTeam(id) {
    return request({
      url: `/team/teams/${id}/`,
      method: 'delete'
    })
  },

  // 获取团队成员（包含贡献时长）
  getTeamMembers(teamId) {
    return request({
      url: `/team/teams/${teamId}/members/`,
      method: 'get'
    })
  },

  // 添加团队成员
  addTeamMember(teamId, data) {
    return request({
      url: `/team/teams/${teamId}/members/`,
      method: 'post',
      data
    })
  },

  // 移除团队成员
  removeTeamMember(teamId, memberId) {
    return request({
      url: `/team/teams/${teamId}/members/${memberId}/`,
      method: 'delete'
    })
  },

  // 开始冲刺
  startSprint(teamId, data) {
    return request({
      url: `/team/teams/${teamId}/sprint/`,
      method: 'post',
      data
    })
  },

  // 获取冲刺数据（包含个人贡献和排行）
  getSprintData(teamId, params = {}) {
    return request({
      url: `/team/teams/${teamId}/sprint/`,
      method: 'get',
      params: {
        user_id: localStorage.getItem('userId'),
        ...params
      }
    })
  },

  // 【新增】获取实时进度数据
  getRealTimeProgress(teamId) {
    return request({
      url: `/team/teams/${teamId}/realtime-progress/`,
      method: 'get'
    })
  },

  // 更新冲刺进度（支持秒级更新）
  updateSprintProgress(teamId, data) {
    return request({
      url: `/team/teams/${teamId}/sprint/`,
      method: 'put',
      data: {
        ...data,
        user_id: parseInt(localStorage.getItem('userId'))
      }
    })
  },

  // 暂停/恢复冲刺
  pauseResumeSprint(teamId, action) {
    return request({
      url: `/team/teams/${teamId}/sprint/`,
      method: 'patch',
      data: {
        action // 'pause' or 'resume'
      }
    })
  },

  // 结束冲刺
  endSprint(teamId) {
    return request({
      url: `/team/teams/${teamId}/sprint/`,
      method: 'delete'
    })
  },

  // 获取排行榜
  getRankings() {
    return request({
      url: '/team/rankings/',
      method: 'get',
      params: {
        user_id: localStorage.getItem('userId')
      }
    })
  },

  // 更新排行榜
  updateRanking(data) {
    return request({
      url: '/team/rankings/',
      method: 'post',
      data: {
        ...data,
        user_id: localStorage.getItem('userId')
      }
    })
  },

  // 获取团队详情
  getTeamDetail(teamId) {
    return request({
      url: `/team/teams/${teamId}/`,
      method: 'get'
    })
  },

  // 获取团队任务列表（包含实时时长）
  getTeamTasks(teamId) {
    return request({
      url: `/team/teams/${teamId}/tasks/`,
      method: 'get'
    })
  },

  // 创建团队任务（支持预估时间和自动开始）
  createTeamTask(teamId, data) {
    return request({
      url: `/team/teams/${teamId}/tasks/`,
      method: 'post',
      data
    })
  },

  // 开始任务
  startTask(teamId, taskId) {
    return request({
      url: `/team/teams/${teamId}/tasks/${taskId}/`,
      method: 'put',
      data: {
        action: 'start'
      }
    })
  },

  // 【新增】暂停任务
  pauseTask(teamId, taskId) {
    return request({
      url: `/team/teams/${teamId}/tasks/${taskId}/`,
      method: 'put',
      data: {
        action: 'pause'
      }
    })
  },

  // 【新增】恢复任务
  resumeTask(teamId, taskId) {
    return request({
      url: `/team/teams/${teamId}/tasks/${taskId}/`,
      method: 'put',
      data: {
        action: 'resume'
      }
    })
  },

  // 【新增】更新任务进度（手动添加时长）
  updateTaskProgress(teamId, taskId, additionalSeconds) {
    return request({
      url: `/team/teams/${teamId}/tasks/${taskId}/`,
      method: 'put',
      data: {
        action: 'update_progress',
        additional_seconds: additionalSeconds
      }
    })
  },

  // 完成团队任务（支持实际耗时）
  completeTeamTask(teamId, taskId, actualSeconds = null) {
    return request({
      url: `/team/teams/${teamId}/tasks/${taskId}/`,
      method: 'put',
      data: {
        action: 'complete',
        actual_seconds: actualSeconds
      }
    })
  },

  // 加入小组
  joinTeam(teamId) {
    return request({
      url: `/team/teams/${teamId}/members/`,
      method: 'post',
      data: {
        user: parseInt(localStorage.getItem('userId'))
      }
    })
  },

  // 退出小组
  leaveTeam(teamId) {
    const userId = parseInt(localStorage.getItem('userId'))
    return request({
      url: `/team/teams/${teamId}/members/${userId}/`,
      method: 'delete'
    })
  },

  // 记录学习时长（新增功能）
  recordStudyTime(teamId, data) {
    return request({
      url: `/team/teams/${teamId}/sprint/`,
      method: 'put',
      data: {
        seconds: data.seconds,
        task_description: data.description || '',
        user_id: parseInt(localStorage.getItem('userId'))
      }
    })
  },

  // 获取个人贡献统计
  getUserContribution(teamId, userId = null) {
    const targetUserId = userId || localStorage.getItem('userId')
    return request({
      url: `/team/teams/${teamId}/sprint/`,
      method: 'get',
      params: {
        user_id: targetUserId,
        detail: true
      }
    })
  },

  // 获取学习活动记录
  getStudyActivities(teamId, params = {}) {
    return request({
      url: `/team/teams/${teamId}/sprint/`,
      method: 'get',
      params: {
        ...params,
        activities: true
      }
    })
  },

  // 工具函数：格式化秒数为时分秒
  formatSeconds(seconds) {
    if (!seconds || seconds < 0) return '00:00:00'
    
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const secs = seconds % 60
    
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  },

  // 工具函数：将时分秒转换为秒数
  parseTimeToSeconds(timeString) {
    if (!timeString) return 0
    
    const parts = timeString.split(':')
    if (parts.length !== 3) return 0
    
    const hours = parseInt(parts[0]) || 0
    const minutes = parseInt(parts[1]) || 0
    const seconds = parseInt(parts[2]) || 0
    
    return hours * 3600 + minutes * 60 + seconds
  },

  // 工具函数：将小时转换为秒
  hoursToSeconds(hours) {
    return Math.floor(hours * 3600)
  },

  // 工具函数：将秒转换为小时
  secondsToHours(seconds) {
    return seconds / 3600
  },

  // 批量更新团队成员贡献（管理员功能）
  batchUpdateContributions(teamId, contributions) {
    return request({
      url: `/team/teams/${teamId}/members/batch-update/`,
      method: 'post',
      data: {
        contributions // Array of {user_id, seconds}
      }
    })
  },

  // 导出团队数据
  exportTeamData(teamId, format = 'json') {
    return request({
      url: `/team/teams/${teamId}/export/`,
      method: 'get',
      params: { format },
      responseType: format === 'csv' ? 'blob' : 'json'
    })
  },

  // 获取团队统计数据
  getTeamStats(teamId, dateRange = null) {
    return request({
      url: `/team/teams/${teamId}/stats/`,
      method: 'get',
      params: {
        start_date: dateRange?.start,
        end_date: dateRange?.end
      }
    })
  }
}

// 【新增】实时更新工具类
export class RealTimeProgressManager {
  constructor(teamId, callbacks = {}) {
    this.teamId = teamId
    this.callbacks = callbacks
    this.timers = new Map() // 存储各种定时器
    this.serverTimeOffset = 0 // 服务器时间偏移
    this.lastUpdateTime = null
  }

  // 开始实时更新
  startRealTimeUpdate() {
    // 立即获取一次数据
    this.fetchRealTimeData()
    
    // 设置定时更新（每15秒从服务器获取最新数据）
    this.timers.set('serverUpdate', setInterval(() => {
      this.fetchRealTimeData()
    }, 15000))

    // 设置本地计时更新（每秒更新一次UI）
    this.timers.set('localUpdate', setInterval(() => {
      this.updateLocalProgress()
    }, 1000))
  }

  // 停止实时更新
  stopRealTimeUpdate() {
    this.timers.forEach((timer) => {
      clearInterval(timer)
    })
    this.timers.clear()
  }

  // 从服务器获取实时数据
  async fetchRealTimeData() {
    try {
      const response = await teamApi.getRealTimeProgress(this.teamId)
      const data = response.data

      // 计算服务器时间偏移
      const serverTime = new Date(data.current_time)
      this.serverTimeOffset = serverTime.getTime() - Date.now()
      this.lastUpdateTime = Date.now()

      // 调用回调函数更新UI
      if (this.callbacks.onProgressUpdate) {
        this.callbacks.onProgressUpdate(data)
      }

      return data
    } catch (error) {
      console.error('获取实时进度失败:', error)
      if (this.callbacks.onError) {
        this.callbacks.onError(error)
      }
    }
  }

  // 本地更新进度（基于本地时间计算）
  updateLocalProgress() {
    if (!this.lastUpdateTime) return

    const now = Date.now()
    const elapsed = Math.floor((now - this.lastUpdateTime) / 1000)

    if (this.callbacks.onLocalTick) {
      this.callbacks.onLocalTick(elapsed)
    }
  }

  // 获取当前服务器时间
  getServerTime() {
    return new Date(Date.now() + this.serverTimeOffset)
  }

  // 暂停特定任务的本地计时
  pauseLocalTask(taskId) {
    const timerId = `task_${taskId}`
    if (this.timers.has(timerId)) {
      clearInterval(this.timers.get(timerId))
      this.timers.delete(timerId)
    }
  }

  // 恢复特定任务的本地计时
  resumeLocalTask(taskId, callback) {
    const timerId = `task_${taskId}`
    this.timers.set(timerId, setInterval(() => {
      if (callback) callback(taskId)
    }, 1000))
  }
}

// 导出增强的工具函数
export const teamUtils = {
  // 格式化时间显示
  formatDuration: teamApi.formatSeconds,
  
  // 解析时间字符串
  parseDuration: teamApi.parseTimeToSeconds,
  
  // 时间单位转换
  hoursToSeconds: teamApi.hoursToSeconds,
  secondsToHours: teamApi.secondsToHours,
  
  // 计算进度百分比
  calculateProgress(completed, target) {
    if (!target || target <= 0) return 0
    return Math.min(100, Math.round((completed / target) * 100))
  },
  
  // 获取状态显示文本
  getStatusText(status) {
    const statusMap = {
      'pending': '待开始',
      'in_progress': '进行中', 
      'paused': '暂停中',
      'completed': '已完成',
      'ongoing': '进行中'
    }
    return statusMap[status] || status
  },
  
  // 获取状态对应的标签类型
  getStatusType(status) {
    const typeMap = {
      'pending': '',
      'in_progress': 'warning',
      'paused': 'info', 
      'completed': 'success',
      'ongoing': 'success'
    }
    return typeMap[status] || ''
  },

  // 【新增】创建实时进度管理器
  createRealTimeManager(teamId, callbacks) {
    return new RealTimeProgressManager(teamId, callbacks)
  },

  // 【新增】计算时间差（用于本地计时）
  calculateElapsedTime(startTime, currentTime = null) {
    const now = currentTime || new Date()
    const start = new Date(startTime)
    return Math.floor((now - start) / 1000)
  },

  // 【新增】格式化相对时间
  formatRelativeTime(timestamp) {
    const now = Date.now()
    const time = new Date(timestamp).getTime()
    const diff = Math.floor((now - time) / 1000)

    if (diff < 60) return `${diff}秒前`
    if (diff < 3600) return `${Math.floor(diff / 60)}分钟前`
    if (diff < 86400) return `${Math.floor(diff / 3600)}小时前`
    return `${Math.floor(diff / 86400)}天前`
  },

  // 【新增】验证任务是否超时
  isTaskOverdue(actualSeconds, estimatedSeconds, status) {
    return status === 'in_progress' && actualSeconds > estimatedSeconds
  },

  // 【新增】计算任务效率
  calculateTaskEfficiency(actualSeconds, estimatedSeconds) {
    if (!estimatedSeconds || estimatedSeconds <= 0) return 100
    return Math.round((estimatedSeconds / actualSeconds) * 100)
  }
}

// 【新增】导出常量
export const TASK_STATUSES = {
  PENDING: 'pending',
  IN_PROGRESS: 'in_progress', 
  PAUSED: 'paused',
  COMPLETED: 'completed'
}

export const SPRINT_STATUSES = {
  ONGOING: 'ongoing',
  PAUSED: 'paused', 
  COMPLETED: 'completed',
  NONE: 'none'
}